﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using store.Areas.Admin.Models;


namespace store.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        private readonly storeEntities _db = new storeEntities();
        private static List<string> _list;

        //
        // GET: /Admin/Product/

        public ActionResult Index()
        {
            ViewBag.Categorys = _db.Categories.ToList();
            return View("Index", _db.Products.ToList());
        }


        //
        // GET: /Admin/Product/Create

        public ActionResult Create()
        {
            ViewBag.Categorys = new SelectList(_db.Categories.ToList().AsEnumerable(), "CategoryID", "Name");
            _list = new List<string>(); // reset anh san pham de upload moi
            var model = new CreateProductModel()
                {
                    CategoryID = 0,
                    Active = true,
                    ProductCode = DateTime.Now.GetHashCode().ToString().Replace('-', ' ').Trim(),
                    Sales = 0,
                };
            return View("Create", model);
        }

        //
        // POST: /Admin/Product/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateProductModel createProductModel)
        {
            ViewBag.Categorys = new SelectList(_db.Categories.ToList().AsEnumerable(), "CategoryID", "Name");
            if (ModelState.IsValid)
            {
                var strPicture = "";
                if (_list != null)
                {
                    foreach (var str in _list)
                    {
                        strPicture += "," + str;
                    }
                }
                if (strPicture.Length < 5)
                {
                    return View("Create", createProductModel);
                }
                var product = new Product()
                {
                    ProductName = createProductModel.ProductName,
                    CategoryID = createProductModel.CategoryID,
                    ProductCode = createProductModel.ProductCode,
                    ShortDesciption = createProductModel.ShortDesciption,
                    DetailDescription = createProductModel.DetailDescription,
                    UnitPrice = createProductModel.UnitPrice,
                    OldPrice = createProductModel.OldPrice,
                    Sales = createProductModel.Sales,
                    Picture = strPicture,
                    Size = createProductModel.Size,
                    Active = createProductModel.Active,
                    ModifiedDate = DateTime.Now.ToLocalTime()
                };
                _db.Products.Add(product);
                _db.SaveChanges();
                if (createProductModel.OptionSubmit == "Lưu và Thêm mới")
                {
                    return RedirectToAction("Create");
                }
                return RedirectToAction("Index");
            }
            return View("Create", createProductModel);
        }

        //
        // GET: /Admin/Product/Edit/5


        public ActionResult Edit(int id = 0)
        {
            _list = new List<string>(); // reset anh san pham de upload
            Product product = _db.Products.Find(id);
            ViewBag.Categorys = new SelectList(_db.Categories.ToList().AsEnumerable(), "CategoryID", "Name");
            if (product == null)
            {
                return HttpNotFound();
            }
            var listsCurrent = product.Picture.Split(',');
            for (int i = 1; i < listsCurrent.Length; i++)
            {
                _list.Add(listsCurrent[i]);
            }
            var editProductModel = new EditProductModel()
                {
                    ProductID = product.ProductID,
                    CategoryID = product.CategoryID,
                    ProductName = product.ProductName,
                    ProductCode = product.ProductCode,
                    Picture = product.Picture,
                    UnitPrice = decimal.Parse(String.Format("{0:0,000}", product.UnitPrice)),
                    Sales = product.Sales,
                    ShortDesciption = product.ShortDesciption,
                    DetailDescription = product.DetailDescription,
                    Color = product.Color,
                    ModifiedDate = DateTime.Now.ToLocalTime(),
                    Active = product.Active != null && (bool)product.Active,

                };
            return View(editProductModel);
        }

        //
        // POST: /Admin/Product/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditProductModel model)
        {
            if (ModelState.IsValid)
            {
                var strPicture = "";
                if (_list != null)
                {
                    foreach (var str in _list)
                    {
                        strPicture += "," + str;
                    }
                }
                if (strPicture.Length < 5)
                {
                    return View("Edit", model);
                }
                //update list picture new
                model.Picture = strPicture;
                Product productUpdate = _db.Products.Find(model.ProductID);
                _db.Entry(productUpdate).CurrentValues.SetValues(model);
                _db.SaveChanges();
                if (model.OptionSubmit == "Lưu và Thoát")
                {
                    return RedirectToAction("Index");
                }
                return RedirectToAction("Edit", new { id = model.ProductID });
            }
            return View(model);
        }

        //
        // GET: /Admin/Product/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Category category = _db.Categories.Find(id);
            if (category == null)
            {
                return HttpNotFound();
            }
            else
            {
                _db.Categories.Remove(category);
                _db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        public ActionResult Upload()
        {
            return PartialView();
        }

        //upload code them
        [HttpPost]
        public JsonResult Upload(IEnumerable<HttpPostedFileBase> files)
        {
            var listPath = new List<string>();
            try
            {
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        // Verify that the user selected a file
                        if (file != null && file.ContentLength > 0)
                        {
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Files"), fileName);
                            string fileNameNew = fileName.GetHashCode().ToString();
                            Image image = Image.FromStream(file.InputStream);
                            //Path.GetExtension()
                            if (image.RawFormat.Equals(ImageFormat.Bmp))
                                fileNameNew += ".bmp";
                            if (image.RawFormat.Equals(ImageFormat.Jpeg))
                                fileNameNew += ".jpg";
                            if (image.RawFormat.Equals(ImageFormat.Png))
                                fileNameNew += ".png";
                            if (image.RawFormat.Equals(ImageFormat.Bmp) || image.RawFormat.Equals(ImageFormat.Jpeg) || image.RawFormat.Equals(ImageFormat.Png))
                            {
                                //xoa neu co san
                                //if (System.IO.File.Exists(Server.MapPath("~/Files/" + fileName)))
                                //    System.IO.File.Delete(Server.MapPath("~/Files/" + fileName));
                                //luu anh
                                //file.SaveAs(path);
                                if (AddWatermark(file.InputStream, fileNameNew))
                                {
                                    SaveThumb(file.InputStream, fileNameNew);
                                    listPath.Add(fileNameNew);
                                    _list.Add(fileNameNew);
                                }

                                //rename
                                //System.IO.File.Move(Server.MapPath("~/Files/" + fileName), Server.MapPath("~/Files/" + fileNameNew));
                                //System.IO.File.Delete(Server.MapPath("~/Files/" + fileName));

                            }

                        }
                    }

                }
            }
            catch (Exception)
            {
            }
            return Json(listPath, JsonRequestBehavior.AllowGet);

        }

        public bool AddWatermark(Stream stream, string filename)
        {

            var pathSave = Server.MapPath("~/Files/" + filename);
            var logo = new Bitmap(Server.MapPath("~/Content/Admin/images/watermarkbg.png"));
            using (var input = new Bitmap(stream))
            {
                int width = input.Width;
                int height = input.Height;
                using (var images = new Bitmap(width, height))
                using (var graphic = Graphics.FromImage(images))
                {
                    const string myCompany = "SHOP 0972.824.581";
                    var font = new Font("Arial", 30f);
                    const int opacityPercent = 80;
                    var waterMarkColor = Color.White;
                    var myBrush = new SolidBrush(Color.FromArgb(opacityPercent, waterMarkColor));
                    var sz = graphic.MeasureString(myCompany, font);
                    var x = (int)(images.Width - sz.Width) / 2; // text center
                    var y = (images.Height) * 0.80;

                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = SmoothingMode.AntiAlias;
                    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                    graphic.DrawImage(input, 0, 0, width, height);
                    graphic.DrawImage(logo, new Rectangle((images.Width - logo.Width) / 2, (int)y - 5, logo.Width, logo.Height), 0, 0, logo.Width, logo.Height, GraphicsUnit.Pixel);
                    graphic.DrawString(myCompany, font, myBrush, new Point(x, (int)y));

                    using (var output = System.IO.File.Create(pathSave))
                    {

                        images.Save(output, ImageFormat.Jpeg);
                        return true;
                    }
                }
            }
        }


        public bool SaveThumb(Stream stream, string filename)
        {

            var pathThumb = Server.MapPath("~/Files/thumb/" + filename);
            using (var input = new Bitmap(stream))
            {
                int width;
                int height;
                if (input.Width > input.Height)
                {
                    width = 240;
                    height = 290 * input.Height / input.Width;
                }
                else
                {
                    height = 290;
                    width = 240 * input.Width / input.Height;
                }
                using (var thumb = new Bitmap(width, height))
                using (var graphic = Graphics.FromImage(thumb))
                {
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = SmoothingMode.AntiAlias;
                    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                    graphic.DrawImage(input, 0, 0, width, height);
                    using (var output = System.IO.File.Create(pathThumb))
                    {

                        thumb.Save(output, ImageFormat.Jpeg);
                        return true;
                    }
                }
            }
        }

        [HttpPost]
        public string DeleteImages(string img)
        {
            _list.Remove(img);
            var pathDelete = Server.MapPath("~/Files/" + img);
            var pathDeleteThumb = Server.MapPath("~/Files/thumb/" + img);
            if (System.IO.File.Exists(pathDelete))
            {
                if (System.IO.File.Exists(pathDeleteThumb))
                {
                    System.IO.File.Delete(pathDeleteThumb);
                }
                System.IO.File.Delete(pathDelete);
                return img;
            }
            return "Xảy ra lỗi.";
        }
    }
}